package com.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.pojo.Category;
import com.reggie.pojo.DishFlavor;
import com.reggie.service.ICategoryService;
import com.reggie.service.IDishFlavorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IDishFlavorService dishFlavorService;

    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info("category:{}",category);
        boolean save = categoryService.save(category);
        if (save){
            return R.success("添加分类成功！");
        }
        return R.error("添加失败,请检查该分类是否已经存在！");
    }

    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize){
        //分页查询
        Page pageBean = new Page(page,pageSize);

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //排序
        lqw.orderByAsc(Category::getSort);
        //获取分页数据
        categoryService.page(pageBean,lqw);
        return R.success(pageBean);
    }

    @DeleteMapping
    public R<String> delete(Long id){
        log.info("删除分类,id为:{}",id);
        categoryService.remove(id);
        return R.success("分类信息删除成功！");

    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
        log.info("修改分类信息:{}",category);

        categoryService.updateById(category);
        return R.success("修改分类信息成功！");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Integer type){

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(type != null,Category::getType,type);
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);
        return R.success(list);

    }
}
